class Solution {
public:
    int leastInterval(vector<char>& tasks, int n) {
        if (n == 0) return tasks.size();
        queue<char> q;
        vector<int> array(26, 0);
        int size = tasks.size();
        for ( int i = 0;  i < size; i++ ) 
            array[tasks[i]-'A'] += 1;
        int count = n + 1;
        int ret = 0;
        while( size > 0 ) 
        {
            for ( int i = 0; i < 26; i++ ) 
            {
                if(array[i] > 0) 
                {
                    q.push(i+'A');
                    array[i] -= 1;
                }
            }
            while(!q.empty() && count > 0) 
            {
                ret++;
                q.pop();
                count--;
                size--;
            }
            while(count > 0 && size > 0) 
            {
                ret++;
                count--;
            }
            count = n + 1;
        }
        return ret;
    }
};
